package com.zzh.partnersys.im.session;

import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

import static com.zzh.partnersys.im.cache.NettyCache.*;


public class SessionMemoryImpl implements Session {

    /**
     * ???
     * @param channel ??? channel ????????
     * @param uid ?????????
     */
    @Override
    public void bind(Channel channel, Long uid) {
        System.out.println("??????uid??+" + uid);
        if (uid == null){
            return;
        }
        ONLINE_WS_MAP.putIfAbsent(uid, channel);
        CHANNEL_UID_MAP.putIfAbsent(channel, uid);
        CHANNEL_ATTRIBUTES_MAP.putIfAbsent(channel, new ConcurrentHashMap<>());
    }

    /**
     * ???
     * @param channel ??? channel ????????
     */
    @Override
    public void unbind(Channel channel) {
        CHANNEL_ATTRIBUTES_MAP.remove(channel);
        Long uid = CHANNEL_UID_MAP.remove(channel);
        if (uid!=null){
            ONLINE_WS_MAP.remove(uid);
        }
        //???????????roup/team??????channel????????ap?????id??????uid???channel?????????????????eam?????????uid
    }

    /**
     * ???
     * @param uid ??? uid ????????
     */
    @Override
    public void unbind(Long uid) {
        Channel channel = ONLINE_WS_MAP.remove(uid);
        if (channel != null){
            CHANNEL_UID_MAP.remove(channel);
            CHANNEL_ATTRIBUTES_MAP.remove(channel);
            channel.close();//?????
        }
        //???????????roup/team??????channel????????ap?????id??????uid???channel?????????????????eam?????????uid
    }

    @Override
    public Object getAttribute(Channel channel, String name) {
        return CHANNEL_ATTRIBUTES_MAP.get(channel).get(name);
    }

    @Override
    public void setAttribute(Channel channel, String name, Object value) {
        CHANNEL_ATTRIBUTES_MAP.get(channel).put(name, value);
    }

    @Override
    public Channel getChannel(Long uid) {
        if (uid == null || uid <= 0){
            return null;
        }
        return ONLINE_WS_MAP.get(uid);
    }

}
